package jjn.hot;

import commons.BinaryTreeHelper;
import commons.TreeNode;

import java.util.*;

/**
 * @author Jjn
 * @since 2023/8/29 22:58
 */
public class LeetCode103 {
    public List<List<Integer>> zigzagLevelOrder(TreeNode root) {
        List<List<Integer>> result = new ArrayList<>();
        if (root == null) {
            return result;
        }
        Deque<TreeNode> queue = new ArrayDeque<>();
        queue.offer(root);
        boolean inverted = false;
        while (!queue.isEmpty()) {
            List<Integer> level = new ArrayList<>();
            int size = queue.size();
            for (int i = 0; i < size; i++) {
                TreeNode node = queue.pollFirst();
                if (node == null) {
                    continue;
                }
                level.add(node.val);
                if (node.left != null) {
                    queue.offer(node.left);
                }
                if (node.right != null) {
                    queue.offer(node.right);
                }
            }
            if (inverted) {
                Collections.reverse(level);
            }
            result.add(level);
            inverted = !inverted;
        }
        return result;
    }
    
    public static void main(String[] args) {
        List<Integer> input = new ArrayList<>();
        input.addAll(List.of(3, 9, 20));
        input.add(null);
        input.add(null);
        input.addAll(List.of(15, 7));
        TreeNode node = BinaryTreeHelper.buildTree(input);
        List<List<Integer>> result = new LeetCode103().zigzagLevelOrder(node);
        result.forEach(System.out::println);
    }
}
